/*
 * @author: wizardc
 */

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Dou.UI
{
    /// <summary>
    /// 点击（Click）事件穿透
    /// 除了自身可以接受点击事件外，还可以让自身下层的第一个监听点击事件的按钮（Button）组件接收到点击事件
    /// 一般用于游戏中的小Tips弹框，要求点击空白区域关闭，同时可以点击到下层按钮的需求，可以给全屏加上透明点击区域，加入该组件即可
    /// </summary>
    public class ButtonEventBroadcast : MonoBehaviour, IPointerClickHandler
    {
        private readonly List<RaycastResult> _raycastResults = new List<RaycastResult>();
        
        public void OnPointerClick(PointerEventData eventData)
        {
            _raycastResults.Clear();
            EventSystem.current.RaycastAll(eventData, _raycastResults);
            foreach (var result in _raycastResults)
            {
                if (result.gameObject != gameObject)
                {
                    GameObject go = FindButton(result.gameObject);
                    if (go != null)
                    {
                        ExecuteEvents.Execute(go, eventData, ExecuteEvents.pointerClickHandler);
                    }
                    break;
                }
            }
            _raycastResults.Clear();
        }
        
        private GameObject FindButton(GameObject go)
        {
            if (go.GetComponent<Button>() != null)
            {
                return go;
            }
            var parent = go.transform.parent;
            while (parent != null)
            {
                if (parent.GetComponent<Button>() != null)
                {
                    return parent.gameObject;
                }
                parent = parent.parent;
            }
            return null;
        }
    }
}
